import React, { Component } from 'react';
import PubSub from 'pubsub-js';
import { Input } from 'antd';
import axios from 'axios';
import './index.css'

class Search extends Component {

  onSearch = (value)=>{
    if(value !== ''){
      // 点击查询按钮后更新状态
      PubSub.publish('users', {isFirst:false, isLoading:true})
      // 调用接口
      let url = `https://api.github.com/search/users?q=${value}`
      axios.get(url).then(
        response =>{
          // console.log('请求成功', response.data)
          // 请求成功后更新状态
          PubSub.publish('users', {isLoading:false, userArr:response.data.items})
        },
        error => {
          // console.log('请求失败', error)
          // 请求报错后更新状态
          PubSub.publish('users', {isLoading:false, err:error.message})
        }
      )}else{
        // 清空输入框后更新状态
        PubSub.publish('users', {isFirst:true})
      }
  }

  render() {
    const {Search} = Input
    return (
      <div className='search'>
        <h2>Search Github Users</h2>
        <Search
          placeholder="enter the name you search"
          allowClear
          enterButton="Search"
          size="large"
          onSearch={this.onSearch}
        />
      </div>
    );
  }
}

export default Search;